package org.mzx.shortLink.adminn.common.Interceptor;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.mzx.shortLink.adminn.common.ThreadLocal.threadlocal;
import org.mzx.shortLink.adminn.common.ThreadLocal.threadlocalDTO;
import org.mzx.shortLink.adminn.common.config.userFlowRiskLimit;
import org.mzx.shortLink.starter.convention.Exception.ClientException;
import org.mzx.shortLink.starter.web.Results;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@Component
@RequiredArgsConstructor
public class userFlowRiskLimitInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    private final userFlowRiskLimit userFlowRiskLimit;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //首先检查有没有开启流控功能
        if (userFlowRiskLimit.getEnable().equals("false")) {
            return true;
        }

        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/admin_flow_risk.lua")));
        redisScript.setResultType(Long.class);

        threadlocalDTO loginUser = threadlocal.getLoginUser();
        //这种情况是用户未登录，那么直接返回false
        if (loginUser==null) {
            return false;
        }
        List<String> keys = new ArrayList<>();
        keys.add(loginUser.getUsername());
        String current = String.valueOf(System.currentTimeMillis());
        Long result = stringRedisTemplate.execute(redisScript, keys, userFlowRiskLimit.getTimeWindow(), current, userFlowRiskLimit.getMaxSize());
        if(result == null||result == 0 ) {
            returnJson(response, JSON.toJSONString(Results.failure(new ClientException("服务器繁忙，请稍后再试"))));
            return false;
        }

        return true;
    }
    private void returnJson(HttpServletResponse response, String json) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(json);
        }
    }
}
